package org.example.order.controller;

import com.github.pagehelper.PageInfo;
import jakarta.annotation.Resource;
import org.example.order.common.APIResponse;
import org.example.order.common.ResponseCode;
import org.example.order.entity.Classification;
import org.example.order.exception.ClassificationNotFoundException;
import org.example.order.permission.Access;
import org.example.order.permission.AccessLevel;
import org.example.order.service.ClassificationService;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/class")
public class ClassificationController {
    @Resource
    private ClassificationService service;

    @GetMapping("/list")
    public APIResponse<PageInfo<Classification>> list(
            @RequestParam(defaultValue = "1") int pageNum,
            @RequestParam(defaultValue = "10") int pageSize
    ) {
        return new APIResponse<>(
                ResponseCode.SUCCESS, service.getClassifications(pageNum, pageSize)
        );
    }

    @GetMapping("/getName")
    public APIResponse<String> getName(@RequestParam Long id) {
        var classification = service.getClassificationById(id);
        if (classification == null) {
            return new APIResponse<>(ResponseCode.NOT_FOUND, "分类id不存在");
        }
        return new APIResponse<>(ResponseCode.SUCCESS, classification.getName());
    }

    @Access(level = AccessLevel.ADMIN)
    @PostMapping("/add")
    public APIResponse<Void> add(@RequestBody Classification classification) {
        try {
            service.addClassification(classification);
        } catch (ClassificationNotFoundException e) {
            return new APIResponse<>(ResponseCode.NOT_FOUND, e.getMessage());
        }
        return new APIResponse<>(ResponseCode.SUCCESS);
    }

    @Access(level = AccessLevel.ADMIN)
    @PostMapping("/update")
    public APIResponse<Void> update(@RequestBody Classification classification) {
        try {
            service.updateClassification(classification);
        } catch (ClassificationNotFoundException e) {
            return new APIResponse<>(ResponseCode.NOT_FOUND, e.getMessage());
        }
        return new APIResponse<>(ResponseCode.SUCCESS);
    }

    @Access(level = AccessLevel.ADMIN)
    @PostMapping("/delete")
    public APIResponse<Void> delete(@RequestBody Classification classification) {
        service.deleteClassification(classification.getId());
        return new APIResponse<>(ResponseCode.SUCCESS);
    }

}
